package de.matusystems;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.URL;
import java.net.URLConnection;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.images.Image;
import com.google.appengine.api.images.Image.Format;
import com.google.appengine.api.images.ImagesService;
import com.google.appengine.api.images.ImagesServiceFactory;
import com.google.appengine.api.images.Transform;

@SuppressWarnings("serial")
public class Img_service_gaeServlet extends HttpServlet {
	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {

		BufferedInputStream bis = null;
		BufferedOutputStream bos = null;

		try {
			URL url = new URL(req.getParameter("url"));
			URLConnection urlc = url.openConnection();

			bis = new BufferedInputStream(urlc.getInputStream());
			bos = new BufferedOutputStream(resp.getOutputStream());

			ByteArrayOutputStream baos = new ByteArrayOutputStream();
			int i;
			while ((i = bis.read()) != -1) {
				baos.write(i);
			}

			byte[] oldImageData = baos.toByteArray();

			ImagesService imagesService = ImagesServiceFactory
					.getImagesService();

			Image oldImage = ImagesServiceFactory.makeImage(oldImageData);
			Image newImage = oldImage;

			Transform transformation = null;

			String action = req.getParameter("action");

			if (action != null && action.equals("resize")) {
				String width = req.getParameter("width");
				String height = req.getParameter("height");

				if (width != null && height != null) {
					transformation = ImagesServiceFactory.makeResize(
							Integer.valueOf(width), Integer.valueOf(height));
				}
			}

			if (transformation != null) {
				newImage = imagesService.applyTransform(transformation,
						oldImage);
			}

			String contentType = "binary/octet-stream";
			if (newImage.getFormat() == Format.JPEG) {
				contentType = "image/jpeg";
			}
			if (newImage.getFormat() == Format.PNG) {
				contentType = "image/png";
			}
			if (newImage.getFormat() == Format.GIF) {
				contentType = "image/gif";
			}

			byte[] newImageData = newImage.getImageData();
			resp.setContentType(contentType);
			resp.getOutputStream().write(newImageData);
		} finally {
			if (bis != null)
				try {
					bis.close();
				} catch (IOException ioe) {
					ioe.printStackTrace();
				}
			if (bos != null)
				try {
					bos.close();
				} catch (IOException ioe) {
					ioe.printStackTrace();
				}
		}

	}
}
